package com.kerrykidz.scmstock.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.activiti.engine.runtime.ProcessInstance;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.kerrykidz.common.Constants;
import com.kerrykidz.scminvoicing.dao.mapper.GblScmPrdEntityMapper;
import com.kerrykidz.scminvoicing.dao.mapper.ScmPrdStgEntityMapper;
import com.kerrykidz.scminvoicing.dao.mapper.ScmStgAdjEntityMapper;
import com.kerrykidz.scminvoicing.dao.mapper.ScmStgadjPrdEntityMapper;
import com.kerrykidz.scminvoicing.dao.mapper.ScmTakeStkEntityMapper;
import com.kerrykidz.scminvoicing.dao.model.GblScmPrdEntity;
import com.kerrykidz.scminvoicing.dao.model.ScmPrdStgEntity;
import com.kerrykidz.scminvoicing.dao.model.ScmStgAdjEntity;
import com.kerrykidz.scminvoicing.dao.model.ScmStgadjPrdEntity;
import com.kerrykidz.scmstock.service.IStockCorrectService;
import com.kerrykidz.system.util.ConstantUtil;
import com.kerrykidz.system.util.DataSourceUtil;
import com.kerrykidz.system.util.ConstantUtil.WorkflowKey;
import com.kerrykidz.system.util.UserUtil;
import com.kerrykidz.system.vo.UserInfo;
import com.kerrykidz.workflow.service.IWorkflowService;
import com.kerrykidz.workflow.vo.WorkflowParamVo;
import com.kerrykidz.workflow.vo.WorkflowVo;
import com.rdp.framework.exception.RDPException;
import com.rdp.util.lang.StringUtil;

@Service
public class StockCorrectServiceImpl implements IStockCorrectService {

	@Autowired
	private ScmStgAdjEntityMapper scmStgAdjEntityMapper;

	@Autowired
	private ScmStgadjPrdEntityMapper scmStgadjPrdEntityMapper;

	@Autowired
	private ScmTakeStkEntityMapper scmTakeStkEntityMapper;

	@Autowired
	private GblScmPrdEntityMapper gblScmPrdEntityMapper;

	@Autowired
	private ScmPrdStgEntityMapper scmPrdStgEntityMapper;

	@Autowired
	private IWorkflowService workflowService;
	
	@Autowired
	DataSourceUtil das;

	/**
	 * 库存调整分页
	 * 
	 * @param startSearchTime
	 *            起始时间
	 * @param endSearchTime
	 *            结束时间
	 * @param scmStgAdj
	 * @return
	 * @throws RDPException
	 */
	public ScmStgAdjEntity findScmStgAdj(String startSearchTime,
			String endSearchTime, ScmStgAdjEntity scmStgAdj, String userId)
			throws RDPException {
		scmStgAdj.setIspaging(true);
		Date startTime = null;
		Date endTime = null;
		UserInfo user = UserUtil.getUserFromSession();
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
			if (startSearchTime == null || startSearchTime.length() == 0) {
				startTime = new Date(0);
			} else {
				startTime = sdf.parse(startSearchTime + " 00:00:00");
			}
			if (endSearchTime != null && endSearchTime.length() != 0) {
				endTime = sdf.parse(endSearchTime + " 23:59:59");
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		scmStgAdj.setStartTime(startTime);
		scmStgAdj.setEndTime(endTime);
		List<ScmStgAdjEntity> beanList = findScmStgAdj(scmStgAdj);
		for (ScmStgAdjEntity s : beanList)
			s.setWorkflowVo(workflowService.getWorkflowVo(s.getFkFlowinstId(),
					s.getStatus(), user));
		if (beanList.size() > 0) {
			scmStgAdj.setResults(beanList);
		}
		return scmStgAdj;
	}

	/**
	 * 根据库存调整单号查询已调整的商品
	 * 
	 * @param fkStgadjId
	 * @return
	 * @throws RDPException
	 */
	public List<ScmStgadjPrdEntity> findScmStgadjPrd(String fkStgadjId)
			throws RDPException {
		return scmStgadjPrdEntityMapper.findScmStgadjPrd(fkStgadjId);
	}

	/**
	 * 列出库存调整单信息
	 * 
	 * @return
	 * @throws RDPException
	 */
	public List<ScmStgAdjEntity> findScmStgAdj(ScmStgAdjEntity scmStgAdj)
			throws RDPException {
		return scmStgAdjEntityMapper.findScmStgAdj(scmStgAdj);
	}

	/**
	 * 获得最新的盘点单号
	 * 
	 * @return 盘点单号
	 * @throws RDPException
	 */
	public String getNewestTake() throws RDPException {
		return scmTakeStkEntityMapper.getNewestTake();
	}

	/**
	 * 插入库存调整单
	 * 
	 * @param scmStgAdj
	 * @throws RDPException
	 */
	public void insertScmStgAdj(ScmStgAdjEntity scmStgAdj) throws RDPException {
		scmStgAdjEntityMapper.insertScmStgAdj(scmStgAdj);
	}

	/**
	 * 插入库存调整清单
	 * 
	 * @param scmStgadjPrd
	 * @throws RDPException
	 */
	public void insertScmStgadjPrd(ScmStgadjPrdEntity scmStgadjPrd)
			throws RDPException {
		scmStgadjPrdEntityMapper.insertScmStgadjPrd(scmStgadjPrd);
	}

	/**
	 * 库存调整清单保存
	 * 
	 * @param scmStgadjPrd
	 * @throws RDPException
	 */
	public String saveScmStgadjPrds(String contents, ScmStgAdjEntity scmStgAdj) {
		try {
			// 添加库存调整单
			insertScmStgAdj(scmStgAdj);
			if (StringUtils.isNotBlank(contents)) {
				String[] content = contents.split("[|]");
				for (String con : content) {
					String[] data = con.split("_");
					if (data[0].length() != 0) {
						ScmStgadjPrdEntity scmStgadjPrd = new ScmStgadjPrdEntity();
						scmStgadjPrd.setFkStgadjId(scmStgAdj.getPkStgadjId());
						scmStgadjPrd.setFkPrdId(data[0].trim());
						scmStgadjPrd.setStgCnt(Integer.parseInt(data[1]));
						// 当前商品有盘点数量
						if (!data[2].equals("null")) {
							scmStgadjPrd.setStkCnt(Integer.parseInt(data[2]));
						}
						scmStgadjPrd.setAdjCnt(Integer.parseInt(data[3]));
						if (data.length > 4) {
							scmStgadjPrd.setComments(data[4]);
						}
						// 插入库存调整清单
						insertScmStgadjPrd(scmStgadjPrd);
					}
				}
				return Constants.SUCCESS;
			}
		} catch (Exception e) {
			return Constants.FAILURE;
		}
		return Constants.FAILURE;
	}

	/**
	 * 库存调整清单提交
	 * 
	 * @param contents
	 * @param scmStgAdj
	 * @return
	 * @throws RDPException
	 */
	@Override
	public String submitScmStgadjPrds(String contents,
			ScmStgAdjEntity scmStgAdj, UserInfo user) {
		try {
			List<ScmStgAdjEntity> beanList = scmStgAdjEntityMapper
					.findScmStgAdj(scmStgAdj);
			if (beanList.size() == 0) {
				saveScmStgadjPrds(contents, scmStgAdj);
			}
			String procId = workflowService.startWorkflow(
					ConstantUtil.getWorkflowKey(WorkflowKey.stock),
					scmStgAdj.getPkStgadjId(), user);
			if(StringUtils.isNotBlank(procId)){
				scmStgAdj.setFkFlowinstId(procId);// 工作流流程实例编号
				scmStgAdj.setStatus("2");// 申请状态
				updateScmStgAdj(scmStgAdj);
				//判断是否是门店
				if(StringUtils.isNotBlank(user.getBranId())){
					//如果是门店的话就进行数据上传
					if(user.getBranId().indexOf("ZB") == -1){
						ScmStgAdjEntity s = scmStgAdjEntityMapper.findScmStgAdjById(scmStgAdj.getPkStgadjId());
						s.setScmStgadjPrd(scmStgadjPrdEntityMapper.findScmStgadjPrd(scmStgAdj.getPkStgadjId()));
						das.executeStock(s,"insert");
					}
				}
			}
			return Constants.SUCCESS;
		} catch (RDPException e) {
			return Constants.FAILURE;
		}
	}

	/**
	 * 库存调整-草稿-编辑
	 * 
	 * @param contents
	 *            添加或需要更新的调整商品信息
	 * @param scmStgAdj
	 *            操作的库存调整单
	 * @param isSubmit
	 *            是否是提交 true 提交 false 保存
	 * @param user
	 * @param prdMap
	 *            判断商品时候已经保存过
	 * @return
	 * @throws RDPException
	 */
	/* (non-Javadoc)
	 * @see com.kerrykidz.scmstock.service.IStockCorrectService#saveScmStgadjPrdsForEdit(com.kerrykidz.workflow.vo.WorkflowParamVo, java.lang.String, com.kerrykidz.scminvoicing.dao.model.ScmStgAdjEntity, java.lang.String, com.kerrykidz.system.vo.UserInfo, java.util.HashMap)
	 */
	public String saveScmStgadjPrdsForEdit(WorkflowParamVo workflowparam,
			String contents, ScmStgAdjEntity scmStgAdj, String isSubmit,
			UserInfo user, HashMap<String, String> prdMap) {
		try {
			
			if (StringUtils.isNotBlank(contents)) {
				String[] content = contents.split("[|]");
				for (String con : content) {
					String[] data = con.split("_");
					if (data[0].length() != 0) {
						ScmStgadjPrdEntity scmStgadjPrd = new ScmStgadjPrdEntity();
						// 如果在数据中已存在调整商品则更新
						String prdId = data[0].trim();
						if (prdMap.get(prdId) != null) {
							scmStgadjPrd.setFkStgadjId(scmStgAdj
									.getPkStgadjId());
							scmStgadjPrd.setFkPrdId(prdId);
							scmStgadjPrd.setAdjCnt(Integer.parseInt(data[3]));
							if (data.length > 4) {
								scmStgadjPrd.setComments(data[4]);
							}
							updateScmStgadjPrd(scmStgadjPrd);
						} else {
							scmStgadjPrd.setFkStgadjId(scmStgAdj
									.getPkStgadjId());
							scmStgadjPrd.setFkPrdId(prdId);
							scmStgadjPrd.setStgCnt(Integer.parseInt(data[1]));
							// 当前商品有盘点数量
							if (!data[2].equals("null")) {
								scmStgadjPrd.setStkCnt(Integer
										.parseInt(data[2]));
							}
							scmStgadjPrd.setAdjCnt(Integer.parseInt(data[3]));
							if (data.length > 4) {
								scmStgadjPrd.setComments(data[4]);
							}
							// 插入库存调整清单
							insertScmStgadjPrd(scmStgadjPrd);
						}
					}
				}
			}
			// 库存调整单已经存在,此时更新
			if (isSubmit.equals("true")) {
				if (StringUtils.isNotBlank(workflowparam.getHandleResult())
						&& workflowparam.getHandleResult().equals("3")) {
					//scmStgAdj.setStatus("2");
					updateScmStgAdj(scmStgAdj);
					int rel = 1;
					//判断是否是门店
					if(StringUtil.isNotBlank(user.getBranId())){
						//如果是门店的话就进行数据上传
						if(user.getBranId().indexOf("ZB") == -1){
							ScmStgAdjEntity s = scmStgAdjEntityMapper.findScmStgAdjById(scmStgAdj.getPkStgadjId());
							s.setScmStgadjPrd(scmStgadjPrdEntityMapper.findScmStgadjPrd(scmStgAdj.getPkStgadjId()));
							rel = das.executeStock(s,"update");
						}
					}
					if(rel > 0){
						// 重新申请
						workflowparam
								.setHandleAdviceDes(ConstantUtil.WORKFLOW_STATUS_REAPPLY);
						workflowService.complete(workflowparam);
					}
				} else {
					String procId = workflowService.startWorkflow(
							ConstantUtil.getWorkflowKey(WorkflowKey.stock),
							scmStgAdj.getPkStgadjId(), user);
					if(StringUtils.isNotBlank(procId)){
						scmStgAdj.setFkFlowinstId(procId);// 工作流流程实例编号
						scmStgAdj.setStatus("2");// 申请状态
						updateScmStgAdj(scmStgAdj);
						//判断是否是门店
						if(StringUtils.isNotBlank(user.getBranId())){
							//如果是门店的话就进行数据上传
							if(user.getBranId().indexOf("ZB") == -1){
								ScmStgAdjEntity s = scmStgAdjEntityMapper.findScmStgAdjById(scmStgAdj.getPkStgadjId());
								s.setScmStgadjPrd(scmStgadjPrdEntityMapper.findScmStgadjPrd(scmStgAdj.getPkStgadjId()));
								das.executeStock(s,"insert");
							}
						}
					}
				}
			}
		} catch (Exception e) {
			return Constants.FAILURE;
		}
		return Constants.SUCCESS;
	}

	/**
	 * 库存调整
	 * 
	 * @param scmStgAdj
	 * @throws RDPException
	 */
	@Override
	public String updateScmStgAdj(ScmStgAdjEntity scmStgAdj) {
		try {
			scmStgAdjEntityMapper.updateScmStgAdj(scmStgAdj);
			return Constants.SUCCESS;
		} catch (RDPException e) {
			return Constants.FAILURE;
		}

	}

	/**
	 * 获得已经调整的商品
	 * 
	 * @param fkStgadjId
	 * @param fkBranId
	 * @return
	 * @throws RDPException
	 */
	public List<GblScmPrdEntity> getSavedCorrectPrds(String fkStgadjId,
			String fkBranId) throws RDPException {
		// 获得已经调整的商品id
		List<ScmStgadjPrdEntity> scmStgadjPrdList = findScmStgadjPrd(fkStgadjId);
		List<GblScmPrdEntity> gsr = new ArrayList<GblScmPrdEntity>();
		for (ScmStgadjPrdEntity s : scmStgadjPrdList) {
			GblScmPrdEntity entity = new GblScmPrdEntity();
			String prdId = s.getFkPrdId().trim();
			entity.setPkPrdId(prdId);
			entity.setFkBranId(fkBranId.trim());
			// 商品id对应的商品信息
			List<GblScmPrdEntity> beans = gblScmPrdEntityMapper
					.findProductListForStock(entity);
			GblScmPrdEntity gsrbean = beans.get(0);
			if (gsrbean != null) {
				gsrbean.setStgCnt(s.getStgCnt());
				gsrbean.setStkCnt(s.getStkCnt());
				gsrbean.setComments(s.getComments());
				gsrbean.setAdjCnt(s.getAdjCnt());
				gsr.add(gsrbean);
			}
		}
		return gsr;

	}

	/**
	 * 更新调整商品
	 * 
	 * @param scmStgadjPrd
	 * @throws RDPException
	 */
	@Override
	public void updateScmStgadjPrd(ScmStgadjPrdEntity scmStgadjPrd)
			throws RDPException {
		scmStgadjPrdEntityMapper.updateScmStgadjPrd(scmStgadjPrd);
	}

	/**
	 * 通过id查询库存调整单,和申请流程历史
	 * 
	 * @param pkStgadjId
	 * @return
	 * @throws RDPException
	 */
	public ScmStgAdjEntity findScmStgAdjById(String pkStgadjId, String userId)
			throws RDPException {
		UserInfo user = UserUtil.getUserFromSession();
		ScmStgAdjEntity scmStgAdj = scmStgAdjEntityMapper
				.findScmStgAdjById(pkStgadjId);
		if (StringUtils.isNotBlank(userId)) {
			WorkflowVo wv = workflowService.getWorkflowVo(
					scmStgAdj.getFkFlowinstId(), scmStgAdj.getStatus(), user);
			// 流程历史
			wv.setOptHisVoList(workflowService.findOpinions(scmStgAdj
					.getFkFlowinstId(),user));
			scmStgAdj.setWorkflowVo(wv);
		}
		return scmStgAdj;
	}

	/**
	 * 处理流程任务
	 * 
	 * @param workflowparam
	 * @throws RDPException
	 */
	@Override
	public void completeStockCorrect(WorkflowParamVo workflowparam,
			String fkBranId, String modiBy) throws RDPException {
		ScmStgAdjEntity scmStgAdj = new ScmStgAdjEntity();
		String stgadjId = workflowparam.getBusinessKey();
		scmStgAdj.setModiBy(workflowparam.getUserInfo().getUserId());
		scmStgAdj.setPkStgadjId(stgadjId);
		scmStgAdj.setStatus("2");
		if (StringUtils.isNotBlank(workflowparam.getHandleResult())) {
			// 递交
			if (workflowparam.getHandleResult().equals("1")) {
					workflowparam.setHandleAdviceDes(workflowparam
							.getHandleAdvice().equals("1") ? "同意" : "不同意");
				ProcessInstance pi = workflowService.complete(workflowparam);
				// 如果已经完成了，修改流程状态
				if (pi == null) {
					if (workflowparam.getHandleAdvice().equals("1")) {// 审批同意
						scmStgAdj.setStatus("3");
						// 调整商品数量
						List<GblScmPrdEntity> gblScmPrd = getSavedCorrectPrds(
								stgadjId, fkBranId);
						for (GblScmPrdEntity bean : gblScmPrd) {
							ScmPrdStgEntity scmPrdStg = new ScmPrdStgEntity();
							scmPrdStg.setFkBranId(fkBranId);
							scmPrdStg.setFkPrdId(bean.getPkPrdId());
							
							scmPrdStg.setModiBy(modiBy);
							ScmPrdStgEntity spsBean = scmPrdStgEntityMapper
									.findScmPrdStg(scmPrdStg);
							if (null != spsBean) {
								// 更新库存
								scmPrdStg.setInstgCnt(0 - bean.getAdjCnt());
								scmPrdStgEntityMapper
										.updateScmPrdStg(scmPrdStg);
							} else {
								scmPrdStg.setStgCnt(0 - bean.getAdjCnt());
								scmPrdStgEntityMapper
										.insertScmPrdStg(scmPrdStg);
							}
							//修改商品表Mode_time
							GblScmPrdEntity prod = new GblScmPrdEntity();
							prod.setPkPrdId(scmPrdStg.getFkPrdId());
							prod.setModiTime(scmPrdStg.getModiTime());
							gblScmPrdEntityMapper.updateEntity(prod);
						}
					} else
						scmStgAdj.setStatus("4");
				}
			} else if (workflowparam.getHandleResult().equals("2")) {
				scmStgAdj.setStatus("2");
				workflowService.backProcessToStart(workflowparam);
			} else if (workflowparam.getHandleResult().equals("4")) {
				// 结束申请
				scmStgAdj.setStatus("5");
				workflowService.deleteProcessInstance(workflowparam);
			}
			updateScmStgAdj(scmStgAdj);
		}
	}

	/**
	 * 根据调整单号和商品号删除调整清单项
	 * 
	 * @param scmStgadjPrd
	 * @throws RDPException
	 */
	@Override
	public void delScmStgadjPrd(ScmStgadjPrdEntity scmStgadjPrd)
			throws RDPException {
		scmStgadjPrdEntityMapper.delScmStgadjPrd(scmStgadjPrd);
	}
}
